const fs = require('fs')
const path = require('path')
const os = require('os')
const { execSync } = require('child_process')
const axios = require('axios')
const userDir = os.homedir()
const sweetCircleFilesFolder = path.join(userDir, '/Documents/SweetCircleFiles')

let userDataFolder = null
let imageFolder = null
let videoFolder = null
let audioFolder = null
let fileFolder = null

const init = (userId) => {
  userDataFolder = path.join(sweetCircleFilesFolder, `/sc_${userId}`)
  imageFolder = path.join(userDataFolder, '/Files/images')
  videoFolder = path.join(userDataFolder, '/Files/videos')
  audioFolder = path.join(userDataFolder, '/Files/audios')
  fileFolder = path.join(userDataFolder, '/Files/Files')
  if (!fs.existsSync(imageFolder)) {
    mkdirs(imageFolder)
  }
  if (!fs.existsSync(videoFolder)) {
    mkdirs(videoFolder)
  }
  if (!fs.existsSync(fileFolder)) {
    mkdirs(fileFolder)
  }
  if (!fs.existsSync(audioFolder)) {
    mkdirs(audioFolder)
  }
}
/**
 * 创建目录
 * @param dir
 */
const mkdirs = (dir) => {
  if (!fs.existsSync(dir)) {
    // 如果目录不存在则进行创建
    const parentDir = path.dirname(dir) // 获取上级目录
    if (parentDir !== dir) {
      // 确保当前目录不为根目录
      mkdirs(parentDir) // 递归调用自身创建上级目录
    }
    fs.mkdirSync(dir) // 创建当前目录
  }
}

const copyFile = ({ type, filePath, fileName, sessionId }) => {
  //图片  201
  //视频  202
  //文件  203
  //语音  204
  //未知  205

  let dist = null
  if (type === 201) {
    dist = path.join(imageFolder, sessionId)
    mkdirs(dist)
    dist = path.join(dist, fileName)
    fs.copyFileSync(filePath, dist)
  } else if (type === 204) {
    dist = path.join(audioFolder, sessionId)
    mkdirs(dist)
    dist = path.join(dist, fileName)
    fs.copyFileSync(filePath, dist)
  } else if (type === 202) {
    dist = path.join(videoFolder, sessionId)
    mkdirs(dist)
    dist = path.join(dist, fileName)
    fs.copyFileSync(filePath, dist)
  } else {
    dist = path.join(fileFolder, sessionId)
    mkdirs(dist)
    dist = path.join(dist, fileName)
    fs.copyFileSync(filePath, dist)
  }
  return dist
}

/**
 * 从视频中获取第一帧并保存为图像
 * @param videoPath 视频文件路径
 */
const getFirstFrameFromVideo = (videoPath) => {
  if (!fs.existsSync(videoPath)) {
    console.error('Video file does not exist.')
    return
  }
  const videoName = path.basename(videoPath, path.extname(videoPath))
  const imageDist = path.join(path.dirname(videoPath), `${videoName}.jpg`)

  try {
    execSync(`ffmpeg -i ${videoPath} -vframes 1 ${imageDist}`)
    console.log(`First frame extracted and saved as ${imageDist}`)
  } catch (error) {
    console.error('Error extracting first frame:', error)
  }
}

const savaFile = (fileName, messageType, userId, sendUserId, token) => {
  axios(import.meta.env.VITE_BASE_URL + '/chat/messageFile', {
    method: 'GET',
    headers: {
      Authorization: 'Bearer ' + token
    },
    params: {
      fileName,
      messageType,
      userId
    },
    responseType: 'stream' // 指定响应类型为流
  }).then((res) => {
    try {
      // 保存文件流res到本地
      if (messageType === 201) {
        //图片
        const filePath = path.join(imageFolder, sendUserId)
        mkdirs(filePath)
        const filePath2 = path.join(filePath, fileName)
        const fileStream = fs.createWriteStream(filePath2)
        res.data.pipe(fileStream)
      }
    } catch (e) {
      console.log(e)
    }
  })
}

export default {
  init,
  copyFile,
  getFirstFrameFromVideo,
  savaFile
}
